
package com.yimi.appstore.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class AsyncPhoneLoader {

    public AsyncPhoneLoader() {
        options.inJustDecodeBounds = false;
        options.inSampleSize = 5;
    }

    private BitmapFactory.Options options = new BitmapFactory.Options();

    private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

    public Drawable loadDrawable(final String imageUrl, final Context context,
            final boolean isSaveIcon, final ImageCallback callback) {
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                callback.imageLoaded((Drawable)msg.obj, imageUrl);
            }
        };
        new Thread() {
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl, context, isSaveIcon);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                handler.sendMessage(handler.obtainMessage(0, drawable));
            };
        }.start();

        return null;
    }
    protected Drawable loadImageFromLocal(String imageUrl, Context context){
    	
        File iconFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/photo/"
                + imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length()));
        if(iconFile.exists()){
        	return BitmapDrawable.createFromPath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/photo/"
                + imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length()));
        }
    	
    	return null;
    }

    protected Drawable loadImageFromUrl(String imageUrl, Context context, boolean isSaveIcon) {
        try {
            if (imageUrl.equals("null") || imageUrl.equals("")) {
                return null;
            }
            HttpURLConnection httpcon = (HttpURLConnection)new URL(imageUrl).openConnection();
            httpcon.setConnectTimeout(20000);
            InputStream is = httpcon.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);

            Drawable drawable = new BitmapDrawable(bitmap);
            if (drawable != null && isSaveIcon) {
                if (Util.isSDCardReady()) {
                    File iconFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/photo/"
                            + imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length()));
                    BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
                    Bitmap bitMap = bitmapDrawable.getBitmap();

                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                            iconFile));
                    bitMap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    stream.flush();
                    stream.close();
                    // bitMap.recycle();
                }
            }
            return drawable;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {

        }
    }

    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }

    public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidht = ((float)w / width);
        float scaleHeight = ((float)h / height);
        matrix.postScale(scaleWidht, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        return newbmp;

    }
}
